package com.jxtc.enterprise.admin.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxtc.enterprise.admin.vo.AdminCompanyDeliveryInfoVO;
import com.jxtc.enterprise.admin.vo.AdminCompanyImageVO;
import com.jxtc.enterprise.admin.vo.AdminCompanyMoreDetailVO;
import com.jxtc.enterprise.admin.vo.AdminViewCompanyDetailVO;
import com.jxtc.enterprise.common.constants.FoodMenuMakerEnum;
import com.jxtc.enterprise.common.constants.MealTypeEnum;
import com.jxtc.enterprise.common.entity.*;
import com.jxtc.enterprise.common.mapper.*;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultCode;
import com.jxtc.enterprise.common.vo.PaginationResponseVO;
import com.jxtc.enterprise.hr.vo.DepartmentVO;
import com.jxtc.enterprise.hr.vo.MealConfigVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.jxtc.enterprise.admin.controller.AdminCompanyManagementController.TL_REQUEST_ID;

@Service
@RequiredArgsConstructor
@Slf4j
public class AdminCompanyManagementService {

    private final CompanyMapper companyMapper;
    private final AdminViewFoodMenuMapper foodMenuAdminViewMapper;
    private final TenantMapper tenantMapper;
    private final MenuStoreConfigMapper menuStoreConfigMapper;
    private final StoreMapper storeMapper;
    private final FoodMapper foodMapper;
    private final DepartmentMapper departmentMapper;

    /**
     * 根据 租户名称，模糊搜索符合条件的租户，并根据租户id，查询出 特定租户所负责的公司
     * 如果 tenantName 为null，则查询所有租户合作的公司
     * @param tenantName
     * @param companyName
     * @param status
     * @param current
     * @param size
     * @return
     */
    public PaginationResponseVO<AdminViewCompanyDetailVO> queryCompanyByPageAdminView(String tenantName, String companyName, int status, int current, int size) {

        // 1. 先根据页面上，租户名输入框输入的租户名，查询出符合条件的 租户

        LambdaQueryWrapper<Tenant> wrapper1 = new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getDelFlag, 0);
        if (StringUtils.isNotEmpty(tenantName)) {
            wrapper1.like(Tenant::getNickname, tenantName).eq(Tenant::getDelFlag, 0); // tenantName 为null时，like语句会被忽略，查询所有租户
        }

        List<Tenant> tenants = tenantMapper.selectList(wrapper1);
        // 没有符合条件的租户，直接返回空
        if (CollectionUtils.isEmpty(tenants)) {
            return new PaginationResponseVO<>(0, 0, Collections.emptyList());
        }

        // 2. 根据租户id，查询 company 表，查询租户负责的公司id
        Page<Company> page = new Page<>(current, size);
        QueryWrapper<Company> wrapper = buildPageQueryWrapper(companyName, status);
        List<String> tenantIds = tenants.stream().map(Tenant::getId).collect(Collectors.toList());
        // 仅返回页面租户名输入框中输入的 租户名 对应的公司，由于输入框支持模糊搜索，因此可能会匹配多个租户，因此此处用 in ('xxx','xxx')
        wrapper.in("tenant_id", tenantIds).eq("del_flag", 0);
        // 得到符合条件的租户id和租户名之间的映射关系，CompanyVO中只有租户id，需要根据租户id得到租户名
        Map<String, String> tenantIdToNameMap = tenants.stream().collect(Collectors.toMap(Tenant::getId, Tenant::getNickname));
        // 查询符合条件的公司信息
        Page<Company> companyPage = companyMapper.selectPage(page, wrapper);

        // 根据查询到的公司信息，拼接得到最终返回给页面的结果
        List<AdminViewCompanyDetailVO> records = new ArrayList<>();
        for (int k = 0; k < companyPage.getRecords().size(); k++) {

            Company company = companyPage.getRecords().get(k);
            AdminViewCompanyDetailVO adminViewCompanyDetailVO = toAdminViewCompanyDetailVO(company, tenantIdToNameMap);
            records.add(adminViewCompanyDetailVO);
        }

        return new PaginationResponseVO<>(companyPage.getTotal(), companyPage.getCurrent(), records);
    }

    /**
     * 将数据库中查询到的 Company 数据转换成对应的 VO
     *
     * @param company 数据库中保存的公司信息
     * @return AdminCompanyDetailVO
     */
    private AdminViewCompanyDetailVO toAdminViewCompanyDetailVO(Company company, Map<String, String> tenantIdToNameMap) {

        String tenantName = tenantIdToNameMap.get(company.getTenantId());
        AdminViewCompanyDetailVO vo = new AdminViewCompanyDetailVO(company, tenantName);

        String imageStr = (company.getImages() != null && !company.getImages().isEmpty()) ? company.getImages() : "{}";
        vo.setImages(JSONUtil.toBean(imageStr, AdminCompanyImageVO.class));

        String deliveryInfoStr = (company.getDeliveryInfo() != null && !company.getDeliveryInfo().isEmpty()) ? company.getDeliveryInfo() : "[]";
        List<CompanyDeliveryInfo> deliveryInfoList = JSONUtil.toList(deliveryInfoStr, CompanyDeliveryInfo.class);

        Optional<CompanyDeliveryInfo> lunchOptional = deliveryInfoList.stream()
                .filter(info -> "午餐".equals(info.getDeliveryType()))
                .findAny();
        if (lunchOptional.isPresent()) {
            AdminCompanyDeliveryInfoVO lunchSetting = new AdminCompanyDeliveryInfoVO(lunchOptional.get());
            vo.setLunchSetting(lunchSetting);
        }

        Optional<CompanyDeliveryInfo> dinnerOptional = deliveryInfoList.stream()
                .filter(info -> "晚餐".equals(info.getDeliveryType()))
                .findAny();
        if (dinnerOptional.isPresent()) {
            AdminCompanyDeliveryInfoVO dinnerSetting = new AdminCompanyDeliveryInfoVO(dinnerOptional.get());
            vo.setDinnerSetting(dinnerSetting);
        }

        return vo;
    }


    private QueryWrapper<Company> buildPageQueryWrapper(String companyName, int status) {
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        if (companyName != null && !companyName.isEmpty()) {
            wrapper.like("name", companyName);
        }

        // 如果查询状态为 "已删除"，del_flag 置 1，否则置 0
        if (status == 4) {
            wrapper.eq("del_flag", 1);
        } else {
            wrapper.eq("del_flag", 0);
        }

        // 如果查询状态为 "正常供餐"，stop_flag 置 0；查询状态为 "停止供餐"，stop_flag 置 1
        if (status == 2) {
            wrapper.eq("stop_flag", 0);
        } else if (status == 3) {
            wrapper.eq("stop_flag", 1);
        }
        return wrapper;
    }

    /**
     * 管理员在公司管理页面，菜单列表，点击 查看菜单按钮，通过公司id查看该公司的所有菜单
     * @param companyId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Result<Object> queryMenusByCompanyId(String companyId, int pageNo, int pageSize) {

        String requestId = TL_REQUEST_ID.get();
        // 1. 查询符合条件的菜单总行数，用于计算分页数据
        int totalRows = foodMenuAdminViewMapper.queryCompanyMenusByCompanyIdByPageCount(companyId);
        // 2. 根据公司id，分页查询某个公司的菜单
        List<HashMap<String, Object>> list = foodMenuAdminViewMapper.queryCompanyMenusByCompanyIdByPage(companyId, (pageNo - 1) * pageSize, pageSize);
        Result<Object> resultData = buildResultData(requestId, list, totalRows, pageSize, pageNo);

        log.info("requestId: {}, response: {}", requestId, resultData);
        return resultData;
    }

    /**
     * 管理员在配置菜单页面，输入租户名，公司名，菜单状态，查询某个租户合作的某个公司的菜单
     * @param tenantName
     * @param companyName
     * @param menuStatus
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Result<Object> queryMenusOfCompany(String tenantName, String companyName, int menuStatus, int pageNo, int pageSize) {

        String requestId = TL_REQUEST_ID.get();
        // 1. 查询符合条件的菜单总行数，用于计算分页数据
        int totalRows = foodMenuAdminViewMapper.queryCompanyMenusByPageCount(tenantName, companyName, menuStatus);
        // 2. 根据公司id，分页查询某个公司的菜单
        List<HashMap<String, Object>> list = foodMenuAdminViewMapper.queryCompanyMenusByPage(tenantName, companyName, menuStatus, (pageNo - 1) * pageSize, pageSize);
        Result<Object> resultData = buildResultData(requestId, list, totalRows, pageSize, pageNo);

        log.info("requestId: {}, response: {}", requestId, resultData);
        return resultData;
    }

    public Result<Object> buildResultData(String requestId, List<HashMap<String, Object>> list, int totalRows, int pageSize, int pageNo) {

        List<JSONObject> formattedCompanyMenus = new ArrayList<>();

        list.forEach(foodMenu -> {

            JSONObject formattedCompanyMenu = new JSONObject();
            formattedCompanyMenu.put("menuId", foodMenu.get("menuId"));
            formattedCompanyMenu.put("companyId", foodMenu.get("companyId"));
            formattedCompanyMenu.put("companyName", foodMenu.get("companyName"));
            formattedCompanyMenu.put("phoneNumber", foodMenu.get("phoneNumber"));
            formattedCompanyMenu.put("hrName", foodMenu.get("hrName"));
            formattedCompanyMenu.put("tenantName", foodMenu.get("tenantName"));
            LocalDateTime startSupplyDateTime = (LocalDateTime) foodMenu.get("commencementDate");
            String formattedTime = Optional.of(startSupplyDateTime).map(time -> time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).orElse("");
            formattedCompanyMenu.put("startSupplyDateTime", formattedTime);
            formattedCompanyMenu.put("menuStatus", foodMenu.get("menuStatus"));
            List<String> mealTypes = new ArrayList<>();
            // 当前company表中，meals_config 列保存的是json格式的字符串，包括各个用餐时段的详细配置，开始，结束时间，用餐时段名称等
            List<MealConfig> mealsConfigVos = JSONArray.parseArray((String) foodMenu.get("mealsConfig"), MealConfig.class);
            log.info("requestId:{}, companyId: {}, company name: {}", requestId, foodMenu.get("companyId"), foodMenu.get("companyName"));
            for (MealConfig mealConfigVo : mealsConfigVos) {
                Boolean enabled = mealConfigVo.getEnabled();
                if (enabled) {
                    // 从各个用餐时段配置VO中仅取出 mealType 用餐时段名称 返回给前端
                    mealTypes.add(mealConfigVo.getMealType());
                }
            }
            formattedCompanyMenu.put("mealTypes", mealTypes);
            formattedCompanyMenus.add(formattedCompanyMenu);
        });

        int totalPages = totalRows % pageSize == 0 ? totalRows / pageSize : totalRows / pageSize + 1;

        Result<Object> result = new Result<>();
        result.setCode(ResultCode.SUCCESS);
        result.setMessage("success");
        JSONObject resultData = new JSONObject();
        resultData.put("currentPage", pageNo);
        resultData.put("totalPages", totalPages);
        resultData.put("totalRows", totalRows);
        resultData.put("data", formattedCompanyMenus);
        result.setData(resultData);

        return result;
    }


    public Result<Object> queryMenuDetailByMealType(String companyId, String menuId, String mealType) {

        String requestId = TL_REQUEST_ID.get();

        List<FoodMenu> storeIdsOfCompanyMenu = foodMenuAdminViewMapper.selectList(
                new LambdaQueryWrapper<FoodMenu>()
                        .eq(FoodMenu::getMenuId, menuId)
                        .eq(FoodMenu::getMealType, mealType)
                        .eq(FoodMenu::getDelFlag, false));
        if (CollectionUtils.isEmpty(storeIdsOfCompanyMenu)) {
            String msg = MessageFormat.format("公司 {0} ,用餐时段: {1} , 没有配置店铺", companyId, mealType);
            log.error("requestId: {}, admin view, /adminView/queryMenuDetailByMealTypeFromAdminView, error, response: {}", requestId, msg);
            Result<Object> result = new Result<>();
            result.setCode(ResultCode.SUCCESS);
            result.setMessage(msg);
            result.setData(null);
            return result;
        }
        Map<String, List<FoodMenu>> storesAndFoodsMap = storeIdsOfCompanyMenu.stream().collect(Collectors.groupingBy(FoodMenu::getStoreId));

        // storeIdsOfCompanyMenu 是某个菜单上的所有菜单项，包括 marker为1，菜单自身；marker为2，为公司挑选的店铺；marker为3，为公司挑选的菜品；此处仅获取为公司配置的店铺
        // 将marker为2的FoodMenu 列表，聚合成map，key为店铺id，value为 店铺对应的FoodMenu 数据项
        Map<String, FoodMenu> storeIdAndFoodMenuMap = storeIdsOfCompanyMenu.stream()
                .filter(menuItem -> menuItem.getMarker().equals(FoodMenuMakerEnum.STORE_MARKER.getCode()))
                // 理论上不会出现 menu_id, store_id 相同，marker为2的多条记录，如果出现，则挑选一个 menu_id不为空的，后面会使用到 menu_id
                .collect(Collectors.toMap(FoodMenu::getStoreId, Function.identity(), (item1, item2) -> StringUtils.isNotEmpty(item1.getMenuId()) ? item1 : item2));
        // 菜单上配置的店铺在 food_menu表中对应的id，通过 id 到多餐功能新增的表 menu_store_config 表中，查找对应的配置项，menu_store_config 表中的menu_item_id 与 food_menu表中，marker为2的记录的 id 对应
        // 注意区分 menu_store_config 表中 menu_id和 menu_item_id 的区别，menu_item_id 是菜单中的某项，marker为2,3的行都属于菜单中的某一项；marker为1的为菜单自身；
        // menu_store_config表中的 menu_id与 food_menu表中的 menu_id对应； menu_store_config 表中的menu_item_id与 food_menu表中的 id 列对应
        List<String> menuItemIdOfStores = storeIdAndFoodMenuMap.values().stream().map(foodMenu -> foodMenu.getId()).collect(Collectors.toList());

        // 查询出各个店铺针对某个公司的菜单，供餐开始，结束，取消截止，预计送达，批量打印的时间
        List<MenuStoreConfig> menuStoreConfigs = menuStoreConfigMapper.selectList(new LambdaQueryWrapper<MenuStoreConfig>()
                .eq(MenuStoreConfig::getMenuId, menuId)
                .eq(MenuStoreConfig::getMealType, mealType)
                .in(MenuStoreConfig::getMenuItemId, menuItemIdOfStores)
                .eq(MenuStoreConfig::getDelFlag, false));
        // key为店铺id，value 为该店铺为公司的某个用餐时段的配置
        Map<String, MenuStoreConfig> storeConfigForOneMealMap = menuStoreConfigs.stream()
                .collect(Collectors.toMap(MenuStoreConfig::getStoreId, Function.identity(), (o1, o2) -> o1));

        List<JSONObject> resultList = new ArrayList<>();
        for (Map.Entry<String, List<FoodMenu>> entry : storesAndFoodsMap.entrySet()) {
            String storeId = entry.getKey();
            Store storeRepositoryDo = storeMapper.selectById(storeId);
            if (storeRepositoryDo == null) {
                log.error("requestId: {}, admin view, /adminView/queryMenuDetailForCompany, error, 无法从 店铺信息库 表中查找到id为 {} 的店铺信息，跳过此店铺", requestId, storeId);
                continue;
            }
            JSONObject formatedStore = new JSONObject();
            // 店铺公共信息，如下信息对各个站点都是一样的
            formatedStore.put("storeId", storeId);
            formatedStore.put("storeName", storeRepositoryDo.getName());
            // 某个店铺为某家公司，供应的多个时段的用餐，返回店铺为公司不同时段用餐的配置的 配置id，页面上其他接口调用时会使用到
            MenuStoreConfig mealConfigByStoreId = storeConfigForOneMealMap.get(storeId);
            if (mealConfigByStoreId == null) {
                // 为公司菜单新挑选的店铺，还未配置各个时间，此时为null
                formatedStore.put("mealConfigId", null); // 为该店铺为公司的某个用餐时段的配置的配置id，对应于 menu_store_config表中的id列
            } else {
                formatedStore.put("mealConfigId", mealConfigByStoreId.getId()); // 为该店铺为公司的某个用餐时段的配置的配置id，对应于 menu_store_config表中的id列
            }
            // 获取food_menu 中，marker为2，店铺id为某个店铺id的 配置项，用于获取 menu_id 和 id 列
            FoodMenu foodMenuForStoreInfo = storeIdAndFoodMenuMap.get(storeId);
            formatedStore.put("menuId", foodMenuForStoreInfo.getMenuId());
            formatedStore.put("menuItemId", foodMenuForStoreInfo.getId()); // 店铺在菜单表中记录的 主键id,用于和 storeMenuConfig 关联时使用
            // key为 菜品类型，value为菜品 列表
            HashMap<String, List<JSONObject>> foods = new HashMap<>();
            for (FoodMenu foodMenu : entry.getValue()) {
                Food foodRepositoryDo = foodMapper.selectById(foodMenu.getFoodId());
                if (foodRepositoryDo == null) {
                    log.error("requestId: {}, admin view, /adminView/queryMenuDetailForCompany, error, 无法从菜品信息库中查找到菜品id为 {} 的菜品, menuId: {}, companyId:{}, storeId: {}",
                            requestId, foodMenu.getFoodId(), foodMenu.getMenuId(), foodMenu.getCompanyId(), foodMenu.getStoreId());
                    continue;
                }

                if (!foods.containsKey(foodRepositoryDo.getFoodTypeName())) {
                    foods.put(foodRepositoryDo.getFoodTypeName(), new ArrayList<>());
                }

                JSONObject foodInfo = new JSONObject();
                foodInfo.put("foodMenuItemId", foodMenu.getId()); // 菜品在菜单表中的记录的组件id，全局唯一，同一个菜品被添加到同一个菜单的不同用餐时段时，此id也是不一样
                foodInfo.put("foodId", foodMenu.getFoodId());
                foodInfo.put("foodName", foodRepositoryDo.getName());
                foodInfo.put("foodImage", foodRepositoryDo.getImage());
                foodInfo.put("limitCount", foodMenu.getLimitCount());
                foodInfo.put("storePrice", foodMenu.getStorePrice());
                foodInfo.put("salePrice", foodMenu.getSalePrice());
                foodInfo.put("showPrice", foodMenu.getShowPrice());
                foodInfo.put("sort", 0);
                foods.get(foodRepositoryDo.getFoodTypeName()).add(foodInfo);
            }

            formatedStore.put("foods", foods);

            resultList.add(formatedStore);
        }

        Result<Object> result = new Result<>();
        result.setCode(ResultCode.SUCCESS);
        result.setMessage("success");
        result.setData(resultList);

        return result;
    }


    public Result<JSONObject> queryStoreConfigForCompany(String requestId, String storeConfigId, String mealType) {
        JSONObject resultData = new JSONObject();
        if (!StringUtils.isNoneEmpty(storeConfigId)) {
            // 首次为公司菜单添加某个店铺时，店铺的用餐时间未配置，使用默认值
            MealTypeEnum mealTypeEnum;
            if (MealTypeEnum.BREAK_FAST.getMealTypeEn().equals(mealType)) {
                mealTypeEnum = MealTypeEnum.BREAK_FAST;
            } else if (MealTypeEnum.LUNCH.getMealTypeEn().equals(mealType)) {
                mealTypeEnum = MealTypeEnum.LUNCH;
            } else if (MealTypeEnum.DINNER.getMealTypeEn().equals(mealType)) {
                mealTypeEnum = MealTypeEnum.DINNER;
            } else if (MealTypeEnum.MORNING_TEA.getMealTypeEn().equals(mealType)) {
                mealTypeEnum = MealTypeEnum.MORNING_TEA;
            } else if (MealTypeEnum.AFTERNOON_TEA.getMealTypeEn().equals(mealType)) {
                mealTypeEnum = MealTypeEnum.AFTERNOON_TEA;
            } else if (MealTypeEnum.NIGHT_SNACK.getMealTypeEn().equals(mealType)) {
                mealTypeEnum = MealTypeEnum.NIGHT_SNACK;
            } else {
                mealTypeEnum = MealTypeEnum.LUNCH;
            }
            resultData.put("startTime", mealTypeEnum.getStartTime());
            resultData.put("endTime", mealTypeEnum.getEndTime());
            resultData.put("canCancelTime", mealTypeEnum.getCanCancelTime());
            resultData.put("deliveryTime", mealTypeEnum.getDeliveryTime());
            resultData.put("printType", mealTypeEnum.getPrintType());
            resultData.put("batchPrintTime", mealTypeEnum.getPrintTime());

        } else {
            MenuStoreConfig menuStoreConfig = menuStoreConfigMapper.selectById(storeConfigId);
            if (menuStoreConfig != null) {
                resultData.put("startTime", menuStoreConfig.getStartTime());
                resultData.put("endTime", menuStoreConfig.getEndTime());
                resultData.put("canCancelTime", menuStoreConfig.getCanCancelTime());
                resultData.put("deliveryTime", menuStoreConfig.getDeliveryTime());
                int printType = menuStoreConfig.getPrintType().equalsIgnoreCase("batch") ? 1 : 2;
                resultData.put("printType", printType);
                resultData.put("batchPrintTime", menuStoreConfig.getPrintTime());
            } else {
                Result<JSONObject> result = new Result<>();
                result.setCode(ResultCode.INTERNAL_SERVER_ERROR);
                result.setMessage("无法查找到该店铺针对公司的配置");
                result.setData(null);
                log.info("requestId {}, admin view, /queryStoreConfigForCompanyAdminView, 无法查找到该店铺针对公司的配置", requestId);
                return result;
            }
        }

        Result<JSONObject> result = new Result<>();
        result.setCode(ResultCode.SUCCESS);
        result.setMessage("success");
        result.setData(resultData);

        return result;
    }


    public AdminCompanyMoreDetailVO queryCompanyDetailById(String companyId){

        // 查询符合条件的公司信息
        Company companyDetail = companyMapper.selectById(companyId);

        QueryWrapper<Department> departmentWrapper = new QueryWrapper<Department>().eq("company_id", companyId);
        List<Department> departments = departmentMapper.selectList(departmentWrapper);

        List<DepartmentVO> departmentVOList = departments.stream()
                .map(department -> new DepartmentVO(department.getId(), department.getName(), department.getAddress()))
                .collect(Collectors.toList());

        return buildCompanyDetailVO(companyDetail, departmentVOList);
    }

    /**
     * 拼接信息，用来展示在 编辑公司 按钮弹窗中，公司基本信息，多餐信息
     * @param company
     * @param departmentVOList
     * @return
     */
    private AdminCompanyMoreDetailVO buildCompanyDetailVO(Company company, List<DepartmentVO> departmentVOList) {
        AdminCompanyMoreDetailVO vo = new AdminCompanyMoreDetailVO();
        vo.setId(company.getId());
        vo.setName(company.getName());
        vo.setAddress(company.getAddress());
        vo.setDepartments(departmentVOList);
        vo.setAutoRecharge(company.getAutoRecharge());
        vo.setThreshold(company.getThreshold());
        vo.setAmount(company.getAmount());
        vo.setHrName(company.getHrName());
        vo.setPhoneNumber(company.getPhoneNumber());
        vo.setPassword(company.getPassword());
        vo.setStopFlag(company.getStopFlag());

        String imageStr = (company.getImages() != null && !company.getImages().isEmpty()) ? company.getImages() : "{}";
        vo.setImages(JSONUtil.toBean(imageStr, AdminCompanyImageVO.class));

        String mealsConfig = (company.getMealsConfig() != null && !company.getMealsConfig().isEmpty()) ? company.getMealsConfig() : "[]";
        List<MealConfig> mealTypes = JSONObject.parseArray(mealsConfig, MealConfig.class);

        // 如果 company 表中的 meals_config 字段是默认值 "[]"，则表示该公司还没有配置默认的配送时间相关信息
        // 此时提供默认 mealTypes 信息
        if (mealTypes.isEmpty()) {
            mealTypes = getDefaultMealConfigList();
        }

        List<MealConfigVO> mealTypeVOList = mealTypes.stream()
                .map(this::buildMealConfigVO)
                .collect(Collectors.toList());
        vo.setMealTypes(mealTypeVOList);
        return vo;
    }

    /**
     * 根据 MealTypeEnum 枚举类中的信息构建默认的用餐时段信息
     */
    private List<MealConfig> getDefaultMealConfigList() {
        List<MealConfig> defaultMealConfigs = new ArrayList<>();

        for (MealTypeEnum mealTypeEnum : MealTypeEnum.values()) {
            MealConfig mealConfig = new MealConfig();
            mealConfig.setMealType(mealTypeEnum.getMealTypeEn());
            mealConfig.setStartTime(mealTypeEnum.getStartTime());
            mealConfig.setEndTime(mealTypeEnum.getEndTime());
            mealConfig.setDeliveryTime(mealTypeEnum.getDeliveryTime());
            mealConfig.setPrintTime(mealTypeEnum.getPrintTime());
            mealConfig.setPrintType(mealTypeEnum.getPrintType());
            // 默认该公司所有订餐时段都是未启用状态
            mealConfig.setEnabled(false);

            defaultMealConfigs.add(mealConfig);
        }

        return defaultMealConfigs;
    }

    /**
     * 将 company 表中的 meals_config 信息转换成前端可用的 mealTypes 信息
     */
    private MealConfigVO buildMealConfigVO(MealConfig mealConfig) {
        MealConfigVO mealConfigVO = new MealConfigVO();
        mealConfigVO.setMealType(mealConfig.getMealType());
        mealConfigVO.setEnabled(mealConfig.getEnabled());
        mealConfigVO.setStartTime(mealConfig.getStartTime());
        mealConfigVO.setEndTime(mealConfig.getEndTime());
        mealConfigVO.setDeliveryTime(mealConfig.getDeliveryTime());
        mealConfigVO.setPrintType(mealConfig.getPrintType());
        mealConfigVO.setPrintTime(mealConfig.getPrintTime());
        return mealConfigVO;
    }

}
